package com.xiemu.ironman.core.service.impl;

import com.xiemu.ironman.core.service.HotDeployService;
import com.xiemu.ironman.core.utils.DeployUtils;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.Set;

public abstract class AbstractHotDeployServiceImpl implements HotDeployService {

    private String jarAddress;

    private ApplicationContext applicationContext;

    public AbstractHotDeployServiceImpl(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /** 删除jar包时 需要在spring容器删除注入 */
    protected void delete(String jarFileName,String jarPth) throws Exception {

        DefaultListableBeanFactory defaultListableBeanFactory =
                (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        //String jarPth = DeployUtils.getJarPth(jarAddress, jarName);
        Set<String> classNameSet = DeployUtils.readJarFile(jarFileName);
        URLClassLoader urlClassLoader =
                new URLClassLoader(
                        new URL[] {new URL(jarPth)},
                        Thread.currentThread().getContextClassLoader());
        for (String className : classNameSet) {
            Class clazz = urlClassLoader.loadClass(className);
            if (DeployUtils.isSpringBeanClass(clazz)) {
                defaultListableBeanFactory.removeBeanDefinition(
                        DeployUtils.transformName(className));
            }
        }
    }
}
